//
//  AppDelegate.swift
//  TestActivityKit
//
//  Created by huihui.zhang on 2023/12/31.
//

import UIKit
import OSLog

@main
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.makeKeyAndVisible()
        window?.rootViewController = UINavigationController(rootViewController: HomeViewController())
        
        //registerNotifications(application)
        
        return true
    }
    
    // MARK: - Nofitication
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        
        let tokenString = deviceToken.reduce("", {$0 + String(format: "%02x", $1)})
        Logger().log("device push token:\(tokenString)")
    }
    
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        // 弹窗提示
    }
    
    // 注册远程推送通知
    func registerNotifications(_ application: UIApplication) {
        let center = UNUserNotificationCenter.current()
        center.delegate = self
        center.getNotificationSettings { (setting) in
            if setting.authorizationStatus == .notDetermined {
                center.requestAuthorization(options: [.badge,.sound,.alert]) { (result, error) in
                    if(result){
                        if !(error != nil){
                            // 注册成功
                            DispatchQueue.main.async {
                                application.registerForRemoteNotifications()
                            }
                        }
                    } else{
                        //用户不允许推送
                    }
                }
            } else if (setting.authorizationStatus == .denied){
                // 申请用户权限被拒
            } else if (setting.authorizationStatus == .authorized){
                // 用户已授权（再次获取dt）
                DispatchQueue.main.async {
                    application.registerForRemoteNotifications()
                }
            } else {
                // 未知错误
            }
        }
    }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        handle(notification: notification, isForeground: true)
    }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        handle(notification: response.notification, isForeground: false)
    }
    
    
    /// 接收到了推送
    /// - Parameters:
    ///   - notification: notification description
    ///   - isForeground: isForeground description
    func handle(notification: UNNotification, isForeground: Bool) {
        guard let trigger = notification.request.trigger, trigger is UNPushNotificationTrigger else {
            // 不是远程推送，是本地推送，
            return
        }
        
        let userInfo = notification.request.content.userInfo
        //let applicationState: UIApplication.State = isForeground ? .active : UIApplication.shared.applicationState
        Logger().log("userInfo:\(userInfo)")
    }
    
}

extension UIFont {
    enum PingFangSCType: String {
        case regular = "PingFangSC-Regular"
        case medium = "PingFangSC-Medium"
        case semibold = "PingFangSC-Semibold"
        case light = "PingFangSC-Light"
        case ultralight = "PingFangSC-Ultralight"
        case thin = "PingFangSC-Thin"
    }
    
    static func PingFang(size: CGFloat, type: PingFangSCType = .regular) -> UIFont {
        if let font = UIFont(name: type.rawValue, size: size) {
            return font
        } else {
            return .systemFont(ofSize: size)
        }
    }
}
